<template>
    <div v-loading="isConnectWebSocket" class="mainArea">
        <div class="top">
            <div class="top-left">
                <div class="title">
                    <p>在线聊天
                        <svg t="1712248283768" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="953" width="20" height="20">
                            <path
                                d="M384 320l512 0c38.4 0 64-25.6 64-64 0-38.4-25.6-64-64-64L384 192C345.6 192 320 217.6 320 256 320 294.4 345.6 320 384 320zM896 448 384 448C345.6 448 320 473.6 320 512c0 38.4 25.6 64 64 64l512 0c38.4 0 64-25.6 64-64C960 473.6 934.4 448 896 448zM896 704 384 704c-38.4 0-64 25.6-64 64 0 38.4 25.6 64 64 64l512 0c38.4 0 64-25.6 64-64C960 729.6 934.4 704 896 704zM128 192C89.6 192 64 217.6 64 256c0 38.4 25.6 64 64 64s64-25.6 64-64C192 217.6 166.4 192 128 192zM128 448C89.6 448 64 473.6 64 512c0 38.4 25.6 64 64 64s64-25.6 64-64C192 473.6 166.4 448 128 448zM128 704c-38.4 0-64 25.6-64 64 0 38.4 25.6 64 64 64s64-25.6 64-64C192 729.6 166.4 704 128 704z"
                                p-id="954"></path>
                        </svg>
                    </p>
                </div>
                <div class="posts" v-for="item in comList" :key="item.id">
                    <div class="post-container" v-if="item.sender == username">
                        <img :src="userAvatar" alt="User Avatar" class="avatar">
                        <div class="post-content">
                            <div style="width:100%">
                                <div class="author-info">
                                    <p class="title">{{ item.sender }}</p>
                                    &nbsp;
                                    <p class="timestamp">
                                        {{ item.timestamp }}
                                    </p>
                                </div>
                                <div class="message">
                                    {{ item.userText }}
                                </div>
                            </div>
                            <button class="reply-button">已读</button>
                        </div>
                    </div>
                    <div v-else class="post-container">
                        <div class="post-content">
                            <button class="reply-button">已读</button>
                            <div style="width:100%">
                                <div class="author-info" style="justify-content: flex-end;">
                                    <p class="timestamp">
                                        {{ item.timestamp }}
                                    </p>
                                    &nbsp;
                                    <p class="title">{{ item.sender }}</p>
                                </div>
                                <div class="message" style="text-align:right">
                                    {{ item.userText }}
                                </div>
                            </div>
                            <img :src="item.avatar" alt="User Avatar" class="avatar">
                        </div>
                    </div>
                </div>
            </div>
            <div class="top-right">
                <div class="profile-card">
                    <div class="profile">
                        <img :src="friendDetails.avatar || '@/assets/images/avatar1.jpg'" alt="Avatar" class="avatar">
                        <div class="user-info">
                            <div class="name">{{ friendDetails.username }}</div>
                            <div class="details">
                                <span class="detail">（学号: {{ friendDetails.id }}）</span>
                            </div>
                        </div>
                    </div>
                    <div class="personal_info">
                        <div class="p-top">
                            <h3>个人信息</h3>
                        </div>
                        <div class="p-bottom">
                            <h4>邮箱: {{ friendDetails.email }}</h4>
                            <h4>班级: {{ friendDetails.className }}</h4>
                            <h4>学校: {{ friendDetails.school }}</h4>
                            <h4>个人介绍:</h4>
                            <h4 style="overflow-auto"> {{ friendDetails.bio }}</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="comment-box">
                <div class="input-area">
                    <h2>功能键区</h2>
                    <textarea v-model="comment" placeholder="请输入内容..."></textarea>
                </div>
                <div class="action-buttons">
                    <button @click="postComment">发送</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, watch, reactive, onUnmounted } from 'vue';
import websocketService from "@/hooks/useWebSocket";
import { useUserStore } from '@/stores/userStore';
import { getUserDetailsById } from '@/service/user/userService';
import router from "@/router"

let username = ref();
const friendShipId = ref();
const friendId = ref();
let isAdminMessageSend = ref(false);
let comList: any = reactive([]);
let isConnectWebSocket = ref(true);
let userStore: any = null;
let userAvatar = ref();
const friendDetails = reactive({
    username: '',
    className: '',
    school: '',
    email: "",
    avatar: '',
    bio: "",
    id: ''
});

onMounted(async () => {

});

// 监听 isConnected 的变化
watch(() => websocketService.isConnected.value, (newValue) => {
    if (newValue) {
        nextTick(() => {
            userStore = useUserStore();
            username.value = userStore.username;
            userAvatar.value = userStore.avatar;
            friendShipId.value = router.currentRoute.value.query.friendShipId;
            friendId.value = router.currentRoute.value.query.friendId;
            fetchFriendDetails(friendId.value);
            isConnectWebSocket.value = false;
            // 订阅消息
            SubScibeFriendMessage();
            window.addEventListener('message-received', handleMessageReceived);
        });
    }
});

onUnmounted(() => {
    window.removeEventListener('message-received', handleMessageReceived);
});

// 发送订阅
const SubScibeFriendMessage = () => {
    websocketService.onSub(`/topic/${friendShipId.value}`);
}

const handleMessageReceived = (event: CustomEvent) => {
    const { sender, content, timestamp } = event.detail;
    if (sender == username.value) return;
    comList.push({
        id: comList.length + 1,
        sender: sender,
        userText: content,
        timestamp: timestamp,
        avatar: friendDetails.avatar

    });
};

const comment = ref('');

const postComment = () => {
    if (!username.value || !friendShipId.value || !comment.value) {
        console.error('All fields are required');
        return;
    }

    const timestamp = new Date().toLocaleString();

    comList.push({
        id: comList.length + 1,
        sender: username.value,
        userText: comment.value,
        timestamp: timestamp,
    });

    websocketService.send(`/app/chat`, {
        sender: username.value,
        room: friendShipId.value,
        type: 'message',
        content: comment.value,
    });

    isAdminMessageSend.value = true;
    comment.value = "";
};
// 获取好友详情
const fetchFriendDetails = async (id: string) => {
    try {
        const response = await getUserDetailsById(id);
        if (response && response.status === 200) {
            Object.assign(friendDetails, response.data);
        } else {
            console.error('获取好友详情失败');
        }
    } catch (error) {
        console.error('获取好友详情失败', error);
    }
};

</script>

<style scoped lang="less"></style>
